/**
 * @Author: easten
 * @Created: 2024-04-15 23:48:14
 * @Description:
 *
 */
import { ApiRole } from "_common/api/sys";
import { DrawerProps } from "_common/DataType";
import { SysRole } from "_common/entity";
import React, { useEffect, useRef } from "react";
import {
  Button,
  Drawer,
  Form,
  FormInstanceFunctions,
  Input,
  InputNumber,
} from "tdesign-react";
import FormItem from "tdesign-react/es/form/FormItem";
type RoleDrawerProps = DrawerProps & {};
const RoleDrawer: React.FC<RoleDrawerProps> = (props: RoleDrawerProps) => {
  const { open, axios, edit, onSuccess, value } = props;
  const formRef = useRef<FormInstanceFunctions>();
  const apiRole = new ApiRole(axios!);

  useEffect(() => {
    return () => {
      formRef.current?.reset();
    };
  }, []);

  useEffect(() => {
    if (value && edit) {
      formRef.current?.setFieldsValue(value);
    }
  }, [edit, value]);

  const handleClose = () => {
    onSuccess?.(false);
    formRef.current?.reset();
  };

  // 新增用户
  const createRole = async (data: SysRole) => {
    const response = await apiRole.createRole(data);
    if (response && response.code === 200) {
      handleClose();
    }
  };
  // 更新用户
  const updateRole = async (data: SysRole) => {
    const response = await apiRole.updateRole({
      ...data,
      id: value?.id,
    });
    if (response && response.code === 200) {
      handleClose();
    }
  };

  return (
    <Drawer
      header={`${edit ? "编辑" : "添加"}角色`}
      footer={false}
      visible={open}
      sizeDraggable
      size="medium"
      onClose={handleClose}
    >
      <Form
        ref={formRef}
        labelWidth={100}
        onSubmit={(data) => {
          edit
            ? updateRole(data.fields as SysRole)
            : createRole(data.fields as SysRole);
        }}
      >
        <FormItem label="角色名称" rules={[{ required: true }]} name="name">
          <Input />
        </FormItem>
        <FormItem label="角色编码" rules={[{ required: true }]} name="code">
          <Input placeholder="角色编码唯一，不要随意改动" />
        </FormItem>
        <FormItem label="排序号" name="sortCode">
          <InputNumber />
        </FormItem>
        <FormItem className="float-right">
          <Button type="submit" theme="primary">
            提交
          </Button>
          <Button type="reset" theme="success" style={{ marginLeft: 12 }}>
            重置
          </Button>
        </FormItem>
      </Form>
    </Drawer>
  );
};
export default RoleDrawer;
